package de.slothsoft.bookmaker.parse.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;

import org.htmlcleaner.CleanerProperties;
import org.htmlcleaner.DomSerializer;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;
import org.w3c.dom.Document;
import org.w3c.dom.xpath.XPathException;

import de.slothsoft.bookmaker.parse.ImageXPathParser;
import de.slothsoft.bookmaker.parse.ParseContext;
import de.slothsoft.bookmaker.parse.WebsiteDescription;
import de.slothsoft.bookmaker.parse.WebsiteParser;
import de.slothsoft.bookmaker.parse.XPathUtil;

public class MangaHereDescription implements WebsiteDescription {

    public static final String REGEX_IMAGE_PREFIX = ".*<img src=\"";
    public static final String REGEX_IMAGE_SUFFIX = "\".*/>";

    public static final String REGEX_CHAPTER = ".*c[0-9]{3}(/){0,1}$";
    public static final String REGEX_URL = "http(s){0,1}://(www.){0,1}mangahere.co/(.*)";

    @Override
    public String getDisplayName() {
        return "mangahere.co";
    }

    @Override
    public boolean isSupported(String url) {
        return url.matches(REGEX_URL) && url.matches(REGEX_CHAPTER);
    }

    @Override
    public WebsiteParser createParser(ParseContext context, InputStream input) throws IOException {
        ImageXPathParser parser = createParser(input);
        context.getProgressMonitor().setStep(0.5 / parser.getPageUrls().size());
        return parser;
    }

    protected static ImageXPathParser createParser(InputStream input) throws IOException {
        try {
            TagNode tagNode = new HtmlCleaner().clean(input);
            Document document = new DomSerializer(new CleanerProperties()).createDOM(tagNode);
            List<String> pageUrls = XPathUtil.findAttributes(document, "//option", "value");
            String title = XPathUtil.findAttribute(document, "/html/head/meta[@property='og:title']", "content");
            if (title != null) {
                title = title.replaceAll(" - Read.* Online", "");
            }
            return ImageXPathParser.createForMangaHere(title, pageUrls);
        } catch (XPathException | ParserConfigurationException | XPathExpressionException e) {
            throw new IOException(e);
        }

    }
}
